package com.mdd.admin.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mdd.admin.validate.commons.PageValidate;
import com.mdd.admin.LikeAdminThreadLocal;
import com.mdd.admin.service.IShopService;
import com.mdd.admin.validate.ShopCreateValidate;
import com.mdd.admin.validate.ShopUpdateValidate;
import com.mdd.admin.validate.ShopSearchValidate;
import com.mdd.admin.vo.ShopListedVo;
import com.mdd.admin.vo.ShopDetailVo;
import com.mdd.common.core.PageResult;
import com.mdd.common.entity.Shop;
import com.mdd.common.exception.OperateException;
import com.mdd.common.mapper.ShopMapper;
import com.mdd.common.util.TimeUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import javax.annotation.Resource;
import java.util.*;

/**
 * 店铺实现类
 * @author DEREK
 */
@Service
public class ShopServiceImpl implements IShopService {
        
    @Resource
    ShopMapper shopMapper;

    /**
     * 店铺列表
     *
     * @author DEREK
     * @param pageValidate 分页参数
     * @param searchValidate 搜索参数
     * @return PageResult<ShopListedVo>
     */
    @Override
    public PageResult<ShopListedVo> list(PageValidate pageValidate, ShopSearchValidate searchValidate) {
        Integer page  = pageValidate.getPageNo();
        Integer limit = pageValidate.getPageSize();

        QueryWrapper<Shop> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id");

        Integer shopId = LikeAdminThreadLocal.getShopId();
        if(null != shopId && shopId > 1) {
        	queryWrapper.eq("id", shopId);
        }
        shopMapper.setSearch(queryWrapper, searchValidate, new String[]{
            "like:name:str",
            "=:icon:str",
            "=:creditScore@credit_score:int",
            "=:businessLicense@business_license:str",
            "=:fans:int",
            "=:remark:str",
            "=:extend:str",
            "=:extend2:str",
            "=:status:int",
        });

        IPage<Shop> iPage = shopMapper.selectPage(new Page<>(page, limit), queryWrapper);

        List<ShopListedVo> list = new LinkedList<>();
        for(Shop item : iPage.getRecords()) {
            ShopListedVo vo = new ShopListedVo();
            BeanUtils.copyProperties(item, vo);
            vo.setCreateTime(TimeUtils.timestampToDate(item.getCreateTime()));
            vo.setUpdateTime(TimeUtils.timestampToDate(item.getUpdateTime()));
            vo.setTotalAmount(item.getTotalAmount().subtract(item.getFreezeAmount()));
            list.add(vo);
        }

        return PageResult.iPageHandle(iPage.getTotal(), iPage.getCurrent(), iPage.getSize(), list);
    }

    /**
     * 店铺详情
     *
     * @author DEREK
     * @param id 主键参数
     * @return Shop
     */
    @Override
    public ShopDetailVo detail(Integer id) {
        Shop model = shopMapper.selectOne(
                new QueryWrapper<Shop>()
                    .eq("id", id)
                    .last("limit 1"));

        Assert.notNull(model, "数据不存在");

        ShopDetailVo vo = new ShopDetailVo();
        BeanUtils.copyProperties(model, vo);
        return vo;
    }

    /**
     * 店铺新增
     *
     * @author DEREK
     * @param createValidate 参数
     */
    @Override
    public void add(ShopCreateValidate createValidate) {
    	 Long count = shopMapper.selectCount(new LambdaQueryWrapper<Shop>()
         		.eq(Shop::getName, createValidate.getName()));
         if(count > 0) {
         	throw new OperateException("店铺名称重复");
         }
         
        Shop model = new Shop();
        model.setName(createValidate.getName());
        model.setLogo(createValidate.getLogo());
        model.setCreditScore(createValidate.getCreditScore());
        model.setBusinessLicense(createValidate.getBusinessLicense());
        model.setFans(createValidate.getFans());
        model.setRemark(createValidate.getRemark());
        model.setExtend(createValidate.getExtend());
        model.setExtend2(createValidate.getExtend2());
        model.setCreateTime(System.currentTimeMillis() / 1000);
        model.setUpdateTime(System.currentTimeMillis() / 1000);
        model.setStatus(createValidate.getStatus());
        shopMapper.insert(model);
    }

    /**
     * 店铺编辑
     *
     * @author DEREK
     * @param updateValidate 参数
     */
    @Override
    public void edit(ShopUpdateValidate updateValidate) {
        Shop model = shopMapper.selectOne(
                new QueryWrapper<Shop>()
                    .eq("id",  updateValidate.getId())
                    .last("limit 1"));

        Assert.notNull(model, "数据不存在!");
        Long count = shopMapper.selectCount(new LambdaQueryWrapper<Shop>()
        		.eq(Shop::getName, updateValidate.getName()).ne(Shop::getId, updateValidate.getId()));
        if(count > 0) {
        	throw new OperateException("店铺名称重复");
        }
        Integer shopId = LikeAdminThreadLocal.getShopId();
        if(shopId > 1) {
        	long daysBetweenDates = TimeUtils.getDaysBetweenDates(new Date(model.getUpdateTime() * 1000), new Date());
        	if(daysBetweenDates < 30) {
        		throw new OperateException("30天内只允许修改一次");
        	}
        }
        model.setId(updateValidate.getId());
        model.setName(updateValidate.getName());
        model.setLogo(updateValidate.getLogo());
        model.setCreditScore(updateValidate.getCreditScore());
        model.setBusinessLicense(updateValidate.getBusinessLicense());
        model.setFans(updateValidate.getFans());
        model.setRemark(updateValidate.getRemark());
        model.setExtend(updateValidate.getExtend());
        model.setExtend2(updateValidate.getExtend2());
        if(shopId > 1) {
        	model.setUpdateTime(System.currentTimeMillis() / 1000);
        }
        model.setStatus(updateValidate.getStatus());
        shopMapper.updateById(model);
    }

    /**
     * 店铺删除
     *
     * @author DEREK
     * @param id 主键ID
     */
    @Override
    public void del(Integer id) {
        Shop model = shopMapper.selectOne(
                new QueryWrapper<Shop>()
                    .eq("id", id)
                    .last("limit 1"));

        Assert.notNull(model, "数据不存在!");

        shopMapper.delete(new QueryWrapper<Shop>().eq("id", id));
    }

	@Override
	public List<ShopListedVo> all() {
		List<Shop> list = shopMapper.selectList(new LambdaQueryWrapper<Shop>());
		List<ShopListedVo> ret = new ArrayList<ShopListedVo>();
		for (Shop shop : list) {
			ShopListedVo vo = new ShopListedVo();
			BeanUtils.copyProperties(shop, vo);
			ret.add(vo);
		}
		return ret;
	}

}
